package com.tinem.platform.service.message.observable;

import com.tinem.platform.module.pojo.enums.message.PushChannel;
import com.tinem.platform.module.pojo.vo.message.PushReq;
import com.tinem.platform.module.starter.web.context.GatewayContext;
import com.tinem.platform.service.message.config.ClientConfiguration;
import com.tinem.platform.service.message.config.MailConfiguration;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.tinem.platform.service.message.config.SmsConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className EMailListener
 * @description TODO
 * @site 
 * @company 
 * @create 2020-09-28 17:55
 */
@Slf4j
@Service
@Order(100)
public class SmsListener implements ApplicationListener<MessageObservable> {
    @Resource
    SmsConfiguration smsConfig;

    @Resource
    ClientConfiguration clientConfiguration;

    @Override
    public void onApplicationEvent(MessageObservable event) {
        if(!event.getSource().getPushChannel().equals(PushChannel.SMS)){
            return;
        }
        if(!(event.getBody() instanceof String)){
            return;
        }
        if(smsConfig.isMock()){
            return;
        }
        ClientConfiguration.Config c = clientConfiguration.getConfig().get(GatewayContext.getClient());
        SmsConfiguration.Config config = smsConfig.getConfig().get(c.getSms());
        PushReq pushReq = event.getSource();
        Map<String, Object> smsParams = new HashMap<String, Object>();
        smsParams.put("appid", config.getAppid());
        smsParams.put("to", pushReq.getTo());
        smsParams.put("signature", config.getSignature());
        smsParams.put("content", event.getBody());
        HttpRequest req = HttpRequest.post(config.getUrl());
        req.charset("UTF-8");
        req.contentType("application/x-www-form-urlencoded; charset=UTF-8");
        log.info("url:({});mobile:({});send body:({});req:({})", config.getUrl(), pushReq.getTo(), event.getBody(), JSON.toJSONString(smsParams));
        String result = req.form(smsParams).timeout(300).execute().body();
        log.info("mobile:({});send body:({});res:({})", pushReq.getTo(), event.getBody(), result);
    }
}
